/* ring_buffer.c: Simple ring buffer API */

#include "ring_buf_serial/ring_buffer_serial.h"


//不支持并发写和读，也没有加入类型 不支持多个端
/* 往队列里存数据 */
int sys_ring_buf_put(struct ring_buf *buf, u8_t *data, u32_t size)
{
	u32_t i, space, index;
    int rc = 0;

	space = sys_ring_buf_space_get(buf);
	if (space >= (size + 1)) {

		if (buf->mask) {
			for (i = 0; i < size; ++i) {
				index = (i + buf->tail) & buf->mask;
				buf->buf[index] = data[i];
			}
			buf->tail = (buf->tail + size) & buf->mask;
		} else {
			for (i = 0; i < size; ++i) {
				index = (i + buf->tail) % buf->size;
				buf->buf[index] = data[i];
			}
			buf->tail = (buf->tail + size) % buf->size;
		}
		rc = 0;
	} else {
		buf->dropped_put_count++;  //!<失败次数记录
		rc = -EMSGSIZE;
	}

	return rc;
}

/* 从队列中取数据 */
int sys_ring_buf_get(struct ring_buf *buf, u8_t *data, u32_t size)
{
	//断言检测读取长度

	u32_t i, index;

	if (sys_ring_buf_is_empty(buf)) {
		return -EAGAIN;
	}

	if (buf->mask) {
		for (i = 0; i < size; ++i) {
			index = (i + buf->head) & buf->mask;
			data[i] = buf->buf[index];
            //buf->buf[index] = 0;
		}
		buf->head = (buf->head + size ) & buf->mask;
	} else {
		for (i = 0; i < size; ++i) {
			index = (i + buf->head) % buf->size;
			data[i] = buf->buf[index];
            //buf->buf[index] = 0;
		}
		buf->head = (buf->head + size) % buf->size;
	}

	return 0;
}

/* 从队列中取出size个数据到data指向的区域 */
int sys_ring_buf_peek(struct ring_buf *buf, u8_t *data, u32_t size)
{
	//断言检测读取长度
	u32_t i, index;

	if (sys_ring_buf_is_empty(buf)) {
		return -EAGAIN;
	}

	if (buf->mask) {
		for (i = 0; i < size; ++i) {
			index = (i + buf->head) & buf->mask;
			data[i] = buf->buf[index];
		}
	} else {
		for (i = 0; i < size; ++i) {
			index = (i + buf->head) % buf->size;
			data[i] = buf->buf[index];
		}
	}

	return 0;
}

/* 清空队列，注意buf清零 */
void sys_ring_buf_clear_empty(struct ring_buf *buf, u32_t size)
{
	//buf->head = 0;
	//buf->tail = 0;
    buf->head = buf->tail;
	buf->dropped_put_count = 0;
    //buff 全清0
    //memset(buf->buf, 0, size);
}
